<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖函数</title>
</head>
<style>
</style>
<body>
    
    <div class="debounce">
        <input type="text">
        <input type="button" value="取消" >
    </div>

    <script>

        function debounce(fn, delay,immediate = true) {
            // 1 设置定时器
            let timer = null
            let flag = true // 设置立即执行的状态
            const _debounce = function (event) {
                // 如果需要立即执行
                if(immediate && flag) {
                    // // 判断上一次的定时器是否存在
                    // if(timer !== null) clearTimeout(timer)
                    // 立即执行
                    fn.call(this,event)
                    flag = false
                    timer = null
                }

                // 2 如果上次的定时器还没有结束 清除上一次的定时器
                if(timer !== null) clearTimeout(timer)
                timer = setTimeout(() => {
                    fn.call(this,event)
                    timer = null
                    // 重置状态
                    flag = true
                },delay)
            }
            return _debounce
        }

        let count = 0
        let input = document.querySelector('input');

        
        input.oninput = debounce(function(event) {
           count ++
           console.log('我是第' + count + '次',this.value,event);
        },200)

    </script>


</body>
</html>